Skip to content

feat: post-PR-#2 hardening — public MCP exposure, SC observability, ordinals naming - #3

Merged
molaanaa merged 8 commits into
molaanaa:mainfrom
EnzinoBB:main
Apr 30, 2026
Merged

molaanaa merged 8 commits into
molaanaa:mainfrom
EnzinoBB:main

Conversation

@EnzinoBB

Copy link
Copy Markdown
Contributor

Summary

Follow-up to merged PR #2: this PR brings on top of main the post-merge hardening that emerged while exposing the MCP publicly, deploying & exercising real on-chain smart contracts, and getting an Anthropic mobile client to actually connect through it. All seven commits are additive and tested (123 unit tests passing locally).

Commit Bucket
0a8de86 feat(mcp): Bearer-token + IP allowlist enforcement on HTTP/SSE security
a0de996 feat(gateway): GATEWAY_HOST env var to bind behind reverse proxy deployment
b04a869 feat(scripts): cross-platform MCP launch scripts (Linux/macOS + Windows) DX
0578f92 docs(readme): 30-second mobile/desktop quick-add for end users docs
55bf98a docs: replace 'ArtVerse' with generic 'ordinals-style on-chain inscription' naming
96973e1 fix(gateway): decode SC return values + map state map+methods correctly gateway bug
9ad65b5 feat(mcp): expose forgetNewState on SC pack/execute (read-only contract reads) gateway/mcp

Highlights

1. Bearer-token + IP allowlist for the public MCP HTTP/SSE endpoint (0a8de86)

The HTTP transport was bound on MCP_HTTP_HOST with no inbound auth — only an outbound bearer for the gateway client and a warning log. Exposing :7000 past localhost meant any external client could enumerate tools and invoke them.

Adds a Starlette BaseHTTPMiddleware that gates both /sse and /messages/:

  • 401 if MCP_AUTH_TOKEN is set and the request omits/mismatches Authorization: Bearer <token>.
  • 403 if MCP_WHITELIST_IPS is set and the client IP is not in the list. The literal 0.0.0.0/0 is treated as a wildcard sentinel that disables the IP gate (Bearer-only).
  • Middleware is only registered when at least one gate is active, so a pure-localhost stdio dev setup keeps zero overhead.

Wires cfg.auth_token and cfg.whitelist_ips through main() so the existing .env.mcp.example knobs actually take effect end-to-end.

2. GATEWAY_HOST env var (a0de996)

Hardcoding host='0.0.0.0' in gateway.py forced the gateway to listen on all interfaces — fine for direct deployments but undesirable behind Nginx + TLS, where the gateway should listen on 127.0.0.1 so :5000 isn't exposed past TLS termination. New GATEWAY_HOST / GATEWAY_PORT env vars (default to the historical 0.0.0.0:5000 so direct deployments are unaffected).

3. Cross-platform launch scripts (b04a869)

scripts/launch-mcp.sh (bash, Linux/macOS) and scripts/launch-mcp.ps1 (PowerShell, Windows). Both perform the same six bootstrap steps: locate Python ≥ 3.10 (the mcp SDK doesn't ship wheels for older versions), reuse-or-create .venv/, install the three runtime deps if missing, source .env.mcp, health-check the gateway, then exec python -m baba_mcp.server. Flags are mirrored: --no-pip / -NoPip, --reinstall / -Reinstall, SKIP_GATEWAY_CHECK=1 / -SkipGatewayCheck, MCP_TRANSPORT=http.

4. README mobile/desktop on-ramp (0578f92)

Added a "Connect from Claude (mobile, desktop, or web) in 30 seconds" subsection at the very top of the MCP section — before any operator material — covering Claude Desktop config, Claude.ai Connectors UI, the mcp+sse:// URI shortcut, plus a note about self-signed certs (with the iOS/Android trust-store install paths). Existing operator content is unchanged.

5. Ordinals naming (55bf98a)

userFields v1 was previously described as the "ArtVerse codec" in the README and skill. ArtVerse is one consumer of the codec, not the codec itself — naming the public API after a single application made it look proprietary, hurt agent discoverability for the more widely-known ordinals/inscription pattern, and tied this PR to BABA branding instead of the underlying technical idea. All user-facing copy now describes the codec as ordinals-style on-chain metadata inscription. The on-chain b"ARTV" MAGIC bytes are kept (back-compat with already-inscribed transactions) and explicitly documented as such.

6. Smart-contract response decode (96973e1)

Surfaced testing the EBB token contract on-chain: every smartcontract_execute call sealed successfully but the gateway returned smartContractResult: null and smartcontract_state returned empty variables / no methods. Three independent mapping bugs:

  • routes/smartcontract.py:_execute_smart_tx was passing the raw Thrift Variant to jsonify, which serialised it as null instead of extracting the primitive. Decode via services.monitor._variant_to_python.
  • The polling fallback path (recovery after TransactionFlow Thrift disconnect) didn't fetch the return value; now also calls TransactionResultGet after the recovered tx_id is found, so the recovered response shape matches the happy path.
  • services/contracts.py:map_state was iterating variables as if it were a list-of-objects, but SmartContractDataResult.variables is map<string, Variant> per the Thrift schema. Rewrote to detect both shapes (real Thrift map + legacy list, for any forks that haven't migrated), decode each Variant to a primitive, and also surface methods (which SmartContractDataResult carries — the only reliable way to read them on this node version, since ContractMethodsGet(address) returns an empty list until the executor's cache fills).

7. forgetNewState on SC pack/execute (9ad65b5)

The Credits node populates TransactionFlowResult.smart_contract_result (the method's return Variant) only when the call is invoked with forgetNewState=true — the standard read-only-call hint. Without it, the transaction persists but the node leaves the result empty, so getters appear to "succeed but return null".

Added forget_new_state (alias forgetNewState) to both SmartContractPackInput and SmartContractExecuteInput. The Pydantic models had extra='forbid' so the field had to be declared on both sides. The gateway already accepted forgetNewState on its /SmartContract/Pack and /SmartContract/Execute payloads — just MCP-side plumbing.

Validation

End-to-end exercise against a live mainnet wallet, EBB token contract EK7Fm4JPmfACz1GYt1yhh917bELfckMDkmDr1eUras6W, MCP reached over public HTTPS via DuckDNS + Let's Encrypt:

=== READ (forgetNewState=true) ===
  getName       → 'EBB'
  getSymbol     → 'EBB'
  getDecimal    → 18
  totalSupply   → '1000000'
  balanceOf(snd) = '999998.50'
  balanceOf(rcv) = '1.50'

=== WRITE (forgetNewState=false, on-chain) ===
  transfer(rcv, '0.25')  → success=True, tx 174759431.1

=== POST-WRITE READ ===
  balanceOf(snd) = '999998.25'   (Δ -0.25 ✓)
  balanceOf(rcv) = '1.75'        (Δ +0.25 ✓)

Test plan

  • pytest tests/ -q → 123 passed (was 121 before this PR; +2 new test_map_state coverage cases for the Thrift-map and methods paths).
  • CI workflow extended in PR Adds the baba-credits Model Context Protocol (MCP) server on top of the existing gateway #2 (Python 3.11 full-suite + Python 3.8 gateway-only) keeps passing on every commit in this PR.
  • Skill drift test (tests/test_skill_drift.py) keeps the catalogue/frontmatter/recipes in sync with the registered MCP tools.
  • Live-node smoke (scripts/mcp_full_smoke.py) still 25/29 PASS / 0 FAIL / 4 SKIP (the 4 SKIPs are node-side limitations confirmed by direct Thrift probe — tokens_* requires monitor API; not a regression).
  • Smart-contract end-to-end exercise on the EBB token (above).

Compatibility & scope

  • Zero breaking changes to existing gateway endpoints. The only existing-handler change is gateway.py's __main__ reading GATEWAY_HOST env vars, defaulting to the previous behaviour.
  • The mapping-fix in services/contracts.py:map_state retains the legacy list-of-objects shape (for older forks) alongside the proper Thrift map<string, Variant> shape.
  • Already-inscribed userFields v1 transactions remain decodable: only docstrings/copy were renamed; the on-chain ARTV MAGIC bytes are unchanged.
  • All new dependencies (mcp, httpx, pydantic) carry python_version >= "3.10" markers from PR Adds the baba-credits Model Context Protocol (MCP) server on top of the existing gateway #2 — Python 3.8 builds remain green.

🤖 Generated with Claude Code

EnzinoBB and others added 8 commits April 30, 2026 06:44
The HTTP transport was previously bound on the configured host with no
inbound auth check — only an outbound bearer for the gateway client and a
warning log. Exposing port 7000 beyond localhost meant any external client
could enumerate tools and invoke them.

Add a Starlette BaseHTTPMiddleware that gates both /sse and /messages/:
- Reject 401 if MCP_AUTH_TOKEN is configured and the request omits or
  mismatches the `Authorization: Bearer <token>` header.
- Reject 403 if MCP_WHITELIST_IPS is configured and the client IP is not
  in the list. The literal "0.0.0.0/0" is treated as a wildcard sentinel
  that disables the IP gate (use Bearer-only auth).
- Middleware is only registered when at least one gate is active, so a
  pure-localhost dev setup (`MCP_HTTP_HOST=127.0.0.1`, no token) keeps
  zero overhead.

Wire cfg.auth_token and cfg.whitelist_ips through main() so the existing
.env.mcp.example knobs actually take effect end-to-end.

.gitignore: add .env.mcp so the production token never gets committed
(matches the pattern already in place for .env, .env.local, .env.smoke).

Tested locally:
- `curl http://0.0.0.0:7000/sse` (no token)             → HTTP 401
- `curl -H 'Authorization: Bearer <good>' .../sse`      → HTTP 200 (SSE)
- `curl -H 'Authorization: Bearer wrong' .../sse`       → HTTP 401

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Hardcoding host='0.0.0.0' in gateway.py forced the gateway to listen on
all interfaces, which is fine for a direct deployment but undesirable
when the gateway sits behind Nginx/Caddy as a reverse proxy with TLS:
exposing :5000 directly bypasses TLS, rate-limiting middleware, and
Bearer auth (for the MCP).

Read GATEWAY_HOST and GATEWAY_PORT from the environment (typically
loaded from .env), defaulting to the historical 0.0.0.0:5000 so direct
deployments keep working unchanged. Reverse-proxy deployments set
GATEWAY_HOST=127.0.0.1 in their .env and stop publishing :5000.

Tested locally:
- GATEWAY_HOST=127.0.0.1 → ss shows 127.0.0.1:5000 only;
  curl http://<public-ip>:5000/api/Diag/GetSupply → connection refused;
  curl https://<public-ip>/api/Diag/GetSupply (via Nginx) → 200 OK.
- Without GATEWAY_HOST → defaults to 0.0.0.0:5000 unchanged.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
scripts/launch-mcp.sh    — bash 4+ script for Linux and macOS.
scripts/launch-mcp.ps1   — PowerShell 5.1+ script for Windows.

Both perform the same bootstrap + sanity sequence and stream coloured
progress (six numbered steps):

1. Locate a Python >= 3.10 interpreter. The `mcp` SDK on PyPI does not
   ship wheels for older versions, so anything earlier than 3.10 is a
   non-starter. The bash version probes python3.13 down to python3,
   the PowerShell version uses the `py -3.x` launcher when available
   then falls back to `python` / `python3` on PATH.
2. Create or reuse `.venv/` next to the repo. If an existing venv is
   pinned to an older Python it gets recreated.
3. `pip install` the three MCP runtime deps (mcp, httpx, pydantic) only
   when missing — `--no-pip` / `-NoPip` skips the check entirely for
   fast relaunches; `--reinstall` / `-Reinstall` forces a reinstall.
4. Source `.env.mcp` if present so BABA_GATEWAY_URL, MCP_TRANSPORT,
   MCP_AUTH_TOKEN, MCP_HTTP_HOST/PORT all flow through with one file.
5. Hit the gateway with a 5-second read-only POST to /api/Diag/GetSupply
   and abort (exit 2) on failure, unless SKIP_GATEWAY_CHECK=1 /
   -SkipGatewayCheck is set.
6. `exec` `python -m baba_mcp.server` so the script's PID becomes the
   server (signals + exit code propagate cleanly).

README "MCP Server" section gains a "Quick start (cross-platform launch
script)" sub-section that documents both invocations + flag matrix
before the existing Configure an Agent walkthrough.

Tested on Linux: end-to-end run reaches step 6, then defers to the
underlying `python -m baba_mcp.server` (which currently fails because
the production MCP is already on :7000 — expected port collision).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The MCP section opened with operator-side topics (pm2 bundle, launch
scripts, signing material) and only got to "how do I plug Claude into a
running server" after ~150 lines. That order is right for the operator
but wrong for the most common end-user path: someone on a phone who just
wants to paste a URL and a token into Claude and start using the tools.

Add a "Connect from Claude in 30 seconds" subsection at the very top of
the MCP section, before any operator material. It covers:

- The two pieces of info to ask the operator for: a URL and a Bearer
  token, with the password-treatment caveat.
- A copy-pasteable JSON snippet that works for both Claude Desktop
  (claude_desktop_config.json) and Claude Code (.mcp.json), with the
  two PASTE-YOUR-* placeholders. After restarting Claude the 29 tools
  appear in the picker; gives a "what's the balance of <wallet>"
  prompt to confirm the connection.
- Instructions for Claude.ai (web/mobile browser) via Settings →
  Connectors → Add custom connector.
- A one-tap `mcp+sse://token@host/sse` URI for clients that support it.
- A heads-up about self-signed certificates: links to the trust-store
  install path on iOS and Android, plus the recommendation to push the
  operator toward Let's Encrypt for a public deployment.
- A signpost down to the operator-side material for readers who want
  to host their own.

Existing operator content (pm2, launch scripts, configure-an-agent
walkthrough, security notes) stays unchanged — this is an additive
on-ramp.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ption'

ArtVerse is one application of the userFields v1 codec, not the codec
itself. Naming the public API after a single consumer made the surface
look proprietary, hurt discoverability for agents reasoning in terms of
the more widely-known "ordinals / inscription" pattern, and tied the
upstream PR to BABA branding instead of the underlying technical idea.

Rewrite all user-facing copy (README, skill, tools-reference, recipe)
to describe the codec as ordinals-style on-chain metadata inscription
(digest + IPFS CID + MIME + size). Triggers in the skill frontmatter
now key off "on-chain ordinal/inscription, userFields metadata" rather
than the previous "ArtVerse mint" trigger phrase.

services/userfields.py: docstring rewritten in the same spirit; the
binary MAGIC bytes "ARTV" are *kept* — they're an on-chain wire-format
constant that any already-inscribed transaction depends on, and changing
them would break decoding of historical user-data blobs. The docstring
now explicitly documents this as a backwards-compat decision.

Internal historical docs (docs/superpowers/*, docs/FOLLOW_UP.md) keep
their original wording — they record what was discussed at the time.

Tests: 121 passed (no behavioural change).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Surfaced testing the EBB token contract (EK7Fm4JPmfACz...): every
smartcontract_execute call sealed on-chain successfully but the gateway
was returning smartContractResult=null and smartcontract_state was
returning empty variables/no methods. Three independent bugs in the
mapping layer.

1. routes/smartcontract.py:_execute_smart_tx — TransactionFlowResult
   carries `smart_contract_result: optional general.Variant` (the method
   return value: e.g. v_string for getSymbol(), v_boolean for
   transfer()). The handler was passing the raw Thrift Variant object
   to jsonify, which serialised it as null instead of extracting the
   primitive. Decode via services.monitor._variant_to_python.

2. routes/smartcontract.py:_execute_smart_tx polling fallback path —
   when TransactionFlow disconnects early, after recovering the sealed
   tx_id via TransactionsGet polling, also call TransactionResultGet to
   pull the smart_contract_result (so the recovered response shape
   matches the happy path).

3. services/contracts.py:map_state — SmartContractDataResult is::

       struct SmartContractDataResult {
           1: APIResponse status
           2: list<SmartContractMethod> methods
           3: map<string, Variant> variables
       }

   The old mapper iterated `variables` as if it were a list-of-objects
   with .name/.type/.value attrs (returning [] for any real-Thrift dict),
   and ignored `methods` entirely. New mapper:
   - Detects map shape and emits one {name, value} entry per key, with
     the Variant decoded to a JSON primitive.
   - Falls back to the legacy list-of-objects shape (NS-style) so the
     unit-test fixtures and any fork variants keep working.
   - Surfaces `methods` (the contract's public surface) — this is the
     only reliable way to read it on this node version, since
     ContractMethodsGet(address) returns an empty list until the
     executor decides to populate its cache.

Tests:
- New test_map_state_handles_thrift_map_variables exercising the
  map<string, Variant> path with v_long + v_string Variants.
- New test_map_state_includes_methods_from_data_get exercising the
  methods passthrough.
- Existing test_map_state_includes_variables relaxed: dropped the
  no-longer-emitted "state" field, kept the list-of-objects coverage.
- 123 passed (was 121).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ct reads)

Validating the EBB token contract on-chain showed that the Credits node
populates TransactionFlowResult.smart_contract_result (the method's
return Variant) only when the call is invoked with forgetNewState=True.
That's the standard read-only-call hint: the executor runs the method,
returns the value, then drops the state mutation. Without it, the
transaction persists but the node leaves smart_contract_result empty —
so getters like getSymbol(), totalSupply(), balanceOf(...) appear to
"succeed but return null" through the gateway.

Add forget_new_state to both:
- SmartContractPackInput (alias forgetNewState, optional)
- SmartContractExecuteInput (alias forgetNewState, default False)

Pydantic models had extra='forbid' so the field had to be declared on
both sides — the gateway already supported `forgetNewState` on its
/SmartContract/Pack and /SmartContract/Execute payloads.

Both endpoints (Pack and Execute) MUST receive the same value: the
canonical signing payload depends on the SmartContractInvocation
serialisation, and forgetNewState is part of that payload. A mismatch
would change the rebuilt inner_id signature and the node would reject
the tx.

Validated: the same contract calls now return:
  getName        → 'EBB'
  getSymbol      → 'EBB'
  getDecimal     → 18
  totalSupply    → '1000000'
  balanceOf(...) → numeric string

And a real transfer (forget=False) followed by post-transfer balanceOf
(forget=True) shows the expected delta: -0.25 sender / +0.25 receiver.

Also (defensive cleanup): removed an experimental 96 KiB SSE-padding
ASGI send wrapper in baba_mcp/server.py:_run_http that was added to try
unsticking Cloudflare Quick Tunnel buffering. Cloudflare Quick Tunnel
turned out to be the wrong path entirely (proper Let's Encrypt cert via
DuckDNS works fine without it), and the wrapper had an exit path that
let starlette receive a None response object on certain race conditions,
producing 'NoneType is not callable' tracebacks. SseNoBufferMiddleware
(X-Accel-Buffering: no header) is the standard nginx-friendly hint and
is sufficient.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@molaanaa
molaanaa merged commit 34f4e1f into molaanaa:main Apr 30, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants